import sys
import ql_fs
import _thread
import utime as time
import ujson as json
from misc import ADC, PWM_V2


CONFIG_PATH = "/usr/config.json"


DEFAULT_ADC_CHANNEL = ADC.ADC0
DEFAULT_PWM_CHANNEL = PWM_V2.PWM0
DEFAULT_PWM_FREQUENCY = 1000.0
DEFAULT_PWM_DUTY = 100


class AutoLight(object):

    def __init__(self):
        self.pwm0 = PWM_V2(DEFAULT_PWM_CHANNEL, DEFAULT_PWM_FREQUENCY, DEFAULT_PWM_DUTY)
        self.adc = ADC()
        self.config = self.__get_config()
        self.tid = None
    
    def __get_config(self):
        if ql_fs.path_exists(CONFIG_PATH):
            with open(CONFIG_PATH, "r") as f:
                return json.load(f)
        else:
            return {"upper_limit": 360, "lower_limit": 20}

    def start(self):
        self.tid = _thread.start_new_thread(self.__run, ())

    def __run(self):
        while True:
            try:
                value = self.adc.read(DEFAULT_ADC_CHANNEL)  # read voltage(mV)
                # print("read voltage: {}".format(value))
            except Exception as e:
                sys.print_exception(e)
                time.sleep(1)
            else:
                self.__set_light_level(value)
                time.sleep_ms(10)
    
    def __set_light_level(self, value):
        upper_limit, lower_limit = self.config["upper_limit"], self.config["lower_limit"]
        if value > upper_limit:
            value = upper_limit
            self.pwm0.open(DEFAULT_PWM_FREQUENCY, 100)
            return
        elif value < lower_limit:
            value = lower_limit
            self.pwm0.close()
        else:
            level = 100 / (upper_limit - lower_limit) * (value - lower_limit)
            self.pwm0.open(DEFAULT_PWM_FREQUENCY, int(level))
            # print("set light level: {}".format(int(level)))


if __name__ == '__main__':
    al = AutoLight()
    al.start()
